package cn.net.autocode.platform.menus.service;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.core.utils.TreeUtils;
import cn.net.autocode.core.utils.UserThreadLocalUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.cache.AutoCacheUtil;
import cn.net.autocode.platform.factory.SpringBeanFactory;
import cn.net.autocode.platform.menus.MenuAnnotation;
import cn.net.autocode.platform.menus.MenuCounter;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("platformMenuServ")
public class MenuServ {

    private final AutoCacheUtil cacheUtil;

    private final Dao dao;


    public MenuServ(AutoCacheUtil cacheUtil, Dao dao) {
        this.cacheUtil = cacheUtil;
        this.dao = dao;
    }

    public Map<String,Integer> menuCounter(List<String> annotationNames){
        Map<String,Integer> counterMap = new HashMap<>();
        List<MenuCounter> beans = SpringBeanFactory.getBeansByType(MenuCounter.class);
        for(MenuCounter menuCounter:beans){
            MenuAnnotation menuAnnotation = menuCounter.getClass().getAnnotation(MenuAnnotation.class);
            if (menuAnnotation!=null){
               String annotationName = menuAnnotation.value();
               if(annotationNames.contains(annotationName)){
                   int num = menuCounter.counter();
                   counterMap.put(annotationName,num);
               }
            }
        }
        return counterMap;
    }



    /**
     * 单位菜单树形结构
     */
    public JSONArray organMenus(boolean disable) {
        String orgCode = UserThreadLocalUtils.getOrgCode();
        //获取菜单信息
        List<String> menuIds = dao.queryListValue("select menu_id from sys_organ_menu where org_code=?",String.class,orgCode);

        //获取公共菜单
        List<String> menuIds2 = dao.queryListValue("select id from sys_menus where is_public='Y'",String.class);
        menuIds.addAll(menuIds2);

        if (!menuIds.isEmpty()){
            String parentSql = "select distinct parent_id from sys_menus where id in (?)  or id in (select parent_id from sys_menus t2 where t2.id in (?))";
            List<String> parentIds = dao.queryListValue(parentSql,String.class,menuIds,menuIds);
            menuIds.addAll(parentIds);
        }

        JSONArray menus = new JSONArray();
        if (!menuIds.isEmpty()) {
            if(disable){
                menus = dao.queryJSONArray("select *,true 'disabled' from sys_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }else{
                menus = dao.queryJSONArray("select * from sys_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }

        }

        return TreeUtils.commonTree(menus);
    }

    /**
     * 单位菜单树形结构
     */
    public JSONArray organAppMenus(boolean disable) {
        String orgCode = UserThreadLocalUtils.getOrgCode();
        //获取菜单信息
        List<String> menuIds = dao.queryListValue("select menu_id from app_organ_menu where org_code=?",String.class,orgCode);


        if (!menuIds.isEmpty()){
            String parentSql = "select distinct parent_id from app_menus where id in (?)  or id in (select parent_id from sys_menus t2 where t2.id in (?))";
            List<String> parentIds = dao.queryListValue(parentSql,String.class,menuIds,menuIds);
            menuIds.addAll(parentIds);
        }

        JSONArray menus = new JSONArray();
        if (!menuIds.isEmpty()) {
            if(disable){
                menus = dao.queryJSONArray("select *,true 'disabled' from app_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }else{
                menus = dao.queryJSONArray("select * from app_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }
        }

        return TreeUtils.commonTree(menus);
    }




    public void menuDeal(JSONArray menus,String isMobile){
        //获取需要计算的菜单
        int len = menus.size();
        List<String> annotationList = new ArrayList<>();
        JSONObject counterMenus = new JSONObject();
        for(int i=0;i<len;i++){
            JSONObject menu = menus.getJSONObject(i);
            if("Y".equals(menu.getString("hasCalc"))&& StrUtil.isNotBlank(menu.getString("calcName"))){
                annotationList.add(menu.getString("calcName").trim());
                counterMenus.put(menu.getString("id"),menu.getString("calcName").trim());
            }
            if (StrUtil.isBlank(menu.getString("icon"))) {
                menu.put("icon","el-icon-folder");
            }
        }

        //记录当前用户需要计算的菜单
        JSONObject user = cacheUtil.getTokenUser(UserThreadLocalUtils.getToken(),isMobile);
        user.put("counterMenus",counterMenus);
        cacheUtil.setToken(UserThreadLocalUtils.getToken(),user,isMobile);

        Map<String,Integer> menuCountMap = this.menuCounter(annotationList);
        for(int i=0;i<len;i++){
            JSONObject menu = menus.getJSONObject(i);
            String annotationName = menu.getString("calcName")==null?"":menu.getString("calcName").trim();
            if("Y".equals(menu.getString("hasCalc"))&& StrUtil.isNotBlank(annotationName)){
                menu.put("counter", menuCountMap.getOrDefault(annotationName, -1));
            }else{
                menu.put("counter",-1);
            }
        }
    }
}
